package com.ruoyi.web.controller.jiugongge;

import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.jiugongge.domain.Jiugongge;
import com.ruoyi.jiugongge.domain.JiugonggeAwards;
import com.ruoyi.jiugongge.domain.JiugonggePrizes;
import com.ruoyi.jiugongge.domain.JiugonggeRelation;
import com.ruoyi.jiugongge.mapper.JiugonggeAwardsMapper;
import com.ruoyi.jiugongge.mapper.JiugonggePrizesMapper;
import com.ruoyi.jiugongge.mapper.JiugonggeRegistrationMapper;
import com.ruoyi.jiugongge.mapper.JiugonggeRelationMapper;
import com.ruoyi.jiugongge.service.IJiugonggeService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.utils.UUIDUtil;
import com.ruoyi.common.utils.WeiXinHttpUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 九宫格活动 信息操作处理
 * 
 * @author lzy
 * @date 2019-01-14
 */
@Controller
@RequestMapping("/jiugongge/jiugongge")
public class JiugonggeController extends BaseController {
	private String prefix = "jiugongge/jiugongge";

	@Autowired
	private IJiugonggeService jiugonggeService;
	@Autowired
	private JiugonggeAwardsMapper jiugonggeAwardsDao;
	@Autowired
	private JiugonggePrizesMapper jiugonggePrizesDao;
	@Autowired
	private JiugonggeRelationMapper jiugonggeRelationDao;
	@Autowired
	private JiugonggeRegistrationMapper jiugonggeRegistrationDao;

	@RequiresPermissions("jiugongge:jiugongge:view")
	@GetMapping()
	public String jiugongge() {
		return prefix + "/jiugongge";
	}
	
	/**
	 * 查询九宫格活动列表
	 */
	@RequiresPermissions("jiugongge:jiugongge:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Jiugongge jiugongge) {
		startPage();
		List<Jiugongge> list = jiugonggeService.selectJiugonggeList(jiugongge);
		return getDataTable(list);
	}

	/**
	 * 导出九宫格活动列表
	 */
	@RequiresPermissions("jiugongge:jiugongge:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(Jiugongge jiugongge) {
		List<Jiugongge> list = jiugonggeService.selectJiugonggeList(jiugongge);
		ExcelUtil<Jiugongge> util = new ExcelUtil<Jiugongge>(Jiugongge.class);
		return util.exportExcel(list, "jiugongge");
	}

	/**
	 * 新增九宫格活动
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存九宫格活动
	 */
	@RequiresPermissions("jiugongge:jiugongge:add")
	@Log(title = "九宫格活动", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	@Transactional
	public AjaxResult addSave(Jiugongge jiugongge) {
		jiugongge.setId(UUIDUtil.creatUUID());
		jiugongge.setCreateTime(new Date());
		jiugongge.setProjectCode("jiugongge");
		int insertJiugongge = jiugonggeService.insertJiugongge(jiugongge);
		List<JiugonggeRelation> awardsList = jiugongge.getAwarsList();
		if (awardsList != null) {
			for (JiugonggeRelation wxActJiugonggeRelation : awardsList) {
				wxActJiugonggeRelation.setId(UUIDUtil.creatUUID());
				wxActJiugonggeRelation.setActId(jiugongge.getId());
				/*
				 * //判断奖项是否为空,为空则增加
				 * 
				 * if(StringUtils.isEmpty(wxActJiugonggeRelation.getAwardId())){
				 * wxActJiugonggeRelation.setAwardId(saveAwards(
				 * wxActJiugonggeRelation.getAwardName())); }else{
				 * JiugonggeAwards wxActJiugonggeAward =
				 * jiugonggeAwardsDao.selectJiugonggeAwardsById(
				 * wxActJiugonggeRelation.getAwardId());
				 * //判断awardId和awardName是否是匹配的，不匹配则增加
				 * if(!wxActJiugonggeAward.getAwardsName().equals(
				 * wxActJiugonggeRelation.getAwardName())){
				 * wxActJiugonggeRelation.setAwardId(saveAwards(
				 * wxActJiugonggeRelation.getAwardName())); } }
				 * 
				 * //判断奖品是否为空,为空则增加
				 * if(StringUtils.isEmpty(wxActJiugonggeRelation.getPrizeId())){
				 * wxActJiugonggeRelation.setPrizeId(savePrizes(
				 * wxActJiugonggeRelation.getPrizeName())); }else{
				 * JiugonggePrizes wxActJiugonggePrize =
				 * jiugonggePrizesDao.selectJiugonggePrizesById(
				 * wxActJiugonggeRelation.getPrizeId());
				 * //prizeId和prizeName是否是匹配的，不匹配则增加
				 * if(!wxActJiugonggePrize.getName().equals(
				 * wxActJiugonggeRelation.getPrizeName())){
				 * wxActJiugonggeRelation.setPrizeId(savePrizes(
				 * wxActJiugonggeRelation.getPrizeName())); }
				 * wxActJiugonggeRelation.setActId(jiugongge.getId());
				 * if(wxActJiugonggeRelation.getProbability()==null){
				 * wxActJiugonggeRelation.setProbability(0d); }
				 * if(wxActJiugonggeRelation.getAmount()==null){
				 * wxActJiugonggeRelation.setAmount(0); } }
				 */
			}
			jiugonggeRelationDao.batchInsert(awardsList);
		}

		return toAjax(insertJiugongge);
	}

	/**
	 * @功能:保存奖项
	 * @作者:lzy
	 * @时间:2019-1-22 上午09:56:47
	 */
	private String saveAwards(String awardName) {
		JiugonggeAwards wxActJiugonggeAwards = new JiugonggeAwards();
		wxActJiugonggeAwards.setAwardsName(awardName);
		/*
		 * String jwid =
		 * ContextHolderUtils.getSession().getAttribute("jwid").toString();
		 * String defaultJwid = WeiXinHttpUtil.getLocalValue("jiugongge",
		 * "defaultJwid"); String createBy =
		 * ContextHolderUtils.getSession().getAttribute("system_userid").
		 * toString();
		 */
		String jwid = "lzyjwid";
		String defaultJwid = "lzy";
		String createBy = ShiroUtils.getLoginName();

		// 如果是H5活动汇
		if (defaultJwid.equals(jwid)) {
			List<JiugonggeAwards> queryAwardsByName = jiugonggeAwardsDao.queryAwardsByName(jwid, createBy, awardName);
			if (queryAwardsByName.size() > 0) {
				return queryAwardsByName.get(0).getId();
			}
			Integer maxAwardsValue = jiugonggeAwardsDao.getMaxAwardsValueByCreateBy(jwid, createBy);
			Integer nextAwardsValue = maxAwardsValue + 1;
			wxActJiugonggeAwards.setAwardsValue(nextAwardsValue);
		} else {
			List<JiugonggeAwards> queryAwardsByName = jiugonggeAwardsDao.queryAwardsByName(jwid, "", awardName);
			if (queryAwardsByName.size() > 0) {
				return queryAwardsByName.get(0).getId();
			}
			Integer maxAwardsValue = jiugonggeAwardsDao.getMaxAwardsValue(jwid);
			if (maxAwardsValue == null) {
				System.out.println("公众号未设置！！！！！！！！！！！！！");
			}
			Integer nextAwardsValue = maxAwardsValue + 1;
			wxActJiugonggeAwards.setAwardsValue(nextAwardsValue);
		}

		wxActJiugonggeAwards.setId(UUIDUtil.creatUUID());
		wxActJiugonggeAwards.setCreateBy(createBy);
		wxActJiugonggeAwards.setJwid(jwid);
		jiugonggeAwardsDao.insertJiugonggeAwards(wxActJiugonggeAwards);
		return wxActJiugonggeAwards.getId();
	}

	/**
	 * @功能:保存奖品
	 * @作者:lzy
	 */
	private String savePrizes(String prizeName) {
		JiugonggePrizes wxActJiugonggePrizes = new JiugonggePrizes();
		/*
		 * String jwid =
		 * ContextHolderUtils.getSession().getAttribute("jwid").toString();
		 * String createBy =
		 * ContextHolderUtils.getSession().getAttribute("system_userid").
		 * toString();
		 */
		String jwid = "lzyjwid";
		String createBy = "lzy";

		// 判断数据库是否已经存在奖品名称
		List<JiugonggePrizes> queryPrizesByName = jiugonggePrizesDao.queryPrizesByName(jwid, createBy, prizeName);
		if (queryPrizesByName.size() > 0) {
			return queryPrizesByName.get(0).getId();
		}
		wxActJiugonggePrizes.setId(UUIDUtil.creatUUID());
		wxActJiugonggePrizes.setCreateBy(createBy);
		wxActJiugonggePrizes.setJwid(jwid);
		wxActJiugonggePrizes.setName(prizeName);
		wxActJiugonggePrizes.setImg("content/jiugongge/img/defaultGoods.png");
		jiugonggePrizesDao.insertJiugonggePrizes(wxActJiugonggePrizes);
		return wxActJiugonggePrizes.getId();
	}

	/**
	 * 修改九宫格活动
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap) {
		Jiugongge jiugongge = jiugonggeService.selectJiugonggeById(id);
		mmap.put("jiugongge", jiugongge);
		return prefix + "/edit";
	}

	/**
	 * 修改保存九宫格活动
	 */
	@RequiresPermissions("jiugongge:jiugongge:edit")
	@Log(title = "九宫格活动", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(Jiugongge jiugongge) {
		return toAjax(jiugonggeService.updateJiugongge(jiugongge));
	}

	/**
	 * 删除九宫格活动
	 */
	@RequiresPermissions("jiugongge:jiugongge:remove")
	@Log(title = "九宫格活动", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(jiugonggeService.deleteJiugonggeByIds(ids));
	}
	
	
	/**
	 * 获取shortUrl
	 * @param id
	 * @return
	 */
	@RequestMapping(value="getShortUrl",method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult getShortUrl(@RequestParam(required = true, value = "id" ) String id){
		try {
			Jiugongge wxActJiugongge = jiugonggeService.selectJiugonggeById(id);
			String shortUrl = wxActJiugongge.getShortUrl();
			if(StringUtils.isEmpty(shortUrl)){
				String hdurl=wxActJiugongge.getHdurl();
				//PropertiesUtil properties=new PropertiesUtil("jiugongge.properties");
				//shortUrl=WeiXinHttpUtil.getShortUrl(hdurl,properties.readProperty("defaultJwid"));
				//shortUrl=WeiXinHttpUtil.getShortUrl(hdurl,"defaultJwid");
				if(StringUtils.isEmpty(shortUrl)){
					shortUrl=hdurl;
				}else{
					jiugonggeService.doUpdateShortUrl(wxActJiugongge.getId(),shortUrl);
				}
			}
			if(StringUtils.isEmpty(shortUrl)){
				return AjaxResult.error("获取地址失败！");
			}else{
				return AjaxResult.success("获取地址成功！",shortUrl);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("获取地址失败！");
		}
	}

}
